package com.youlu.campus.monitor.service.impl;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.monitor.entity.WechatMonitorTask;
import com.youlu.campus.monitor.entity.WechatMonitorTaskPageQuery;
import com.youlu.campus.monitor.repositories.WechatMonitorTaskRepository;
import com.youlu.campus.monitor.service.WechatMonitorTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 微信监控任务业务逻辑实现类
 * 处理业务校验、异常抛出，返回业务对象，不封装QResult
 *
 * @author su
 * @date 2025/09/02
 */
@Service
@Slf4j
public class WechatMonitorTaskServiceImpl implements WechatMonitorTaskService {

    @Resource
    private WechatMonitorTaskRepository taskRepository;

    @Resource
    private MongoTemplate wechatMonitorMongoTemplate;

    @Override
    public WechatMonitorTask saveTask(WechatMonitorTask task) {
        // 业务参数校验
        Assert.notNull(task, "任务实体不能为null");
        Assert.hasText(task.getName(), "任务名称不能为空");
        Assert.hasText(task.getWechatName(), "微信名称不能为空");
        Assert.hasText(task.getWechatType(), "微信类型不能为空");
        Assert.hasText(task.getWeekday(), "执行星期（weekday）不能为空");
        Assert.hasText(task.getHour(), "执行小时（hour）不能为空");
        Assert.hasText(task.getMinute(), "执行分钟（minute）不能为空");
        // 新增任务（MongoDB自动生成id）
        if (StringUtils.isBlank(task.getId())) {
            task.setCreateTime(LocalDateTime.now());
        } else {
            Optional<WechatMonitorTask> optional = taskRepository.findById(task.getId());
            if (!optional.isPresent()) {
                throw new BusinessException("数据不存在");
            }
            task.setCreateTime(optional.get().getCreateTime());
            task.setUpdateTime(LocalDateTime.now());
        }
        // 中文逗号转英文逗号 处理
        if (StringUtils.isNotBlank(task.getWeekday())) {
            String weekday = task.getWeekday().replaceAll("，", ",");
            task.setWeekday(weekday);
        }
        if (StringUtils.isNotBlank(task.getHour())) {
            String hour = task.getHour().replaceAll("，", ",");
            task.setHour(hour);
        }
        if (StringUtils.isNotBlank(task.getMinute())) {
            String minute = task.getMinute().replaceAll("，", ",");
            task.setMinute(minute);
        }
        String wechatName = task.getWechatName().trim();
        if (wechatName.contains(" ")) {
            throw new BusinessException("微信名称不能包含空格");
        }
        wechatName = wechatName.replaceAll("，", ",");
        String[] split = wechatName.split(",");
        split = Arrays.stream(split).distinct().toArray(String[]::new);
        if (split.length > 10) {
            throw new BusinessException("一次配置微信不能超过10个");
        }
        task.setWechatName(String.join(",", split));
        WechatMonitorTask savedTask = taskRepository.save(task);
        log.info("新增微信监控任务成功，任务id：{}，任务名称：{}", savedTask.getId(), savedTask.getName());
        return savedTask;

    }

    @Override
    public boolean deleteTaskById(String id) {
        // 参数校验
        Assert.hasText(id, "任务id不能为空");
        // 执行删除
        taskRepository.deleteById(id);
        return true;

    }

    @Override
    public WechatMonitorTask getTaskById(String id) {
        // 参数校验
        Assert.hasText(id, "任务id不能为空");
        Optional<WechatMonitorTask> taskOpt = taskRepository.findById(id);
        log.info("查询微信监控任务详情成功，任务id：{}", id);
        return taskOpt.orElse(null);
    }

    @Override
    public Page<WechatMonitorTask> findByPage(WechatMonitorTaskPageQuery pageQuery) {
        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getName())) {
            query.addCriteria(Criteria.where("name").regex(pageQuery.getName(), "i"));
        }
        if (StringUtils.isNotBlank(pageQuery.getWechatName())) {
            query.addCriteria(Criteria.where("wechatName").regex(pageQuery.getWechatName(), "i"));
        }
        if (StringUtils.isNotBlank(pageQuery.getWechatType())) {
            query.addCriteria(Criteria.where("wechatType").is(pageQuery.getWechatType()));
        }
        //统计总条数（分页需要先查总数）
        long total = wechatMonitorMongoTemplate.count(query, WechatMonitorTask.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("createTime").descending());
        List<WechatMonitorTask> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = wechatMonitorMongoTemplate.find(query, WechatMonitorTask.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);

    }

    @Override
    public List<WechatMonitorTask> listAllTasks() {
        try {
            List<WechatMonitorTask> taskList = taskRepository.findAll();
            log.info("查询所有微信监控任务成功，总条数：{}", taskList.size());
            return taskList;
        } catch (Exception e) {
            log.error("查询所有微信监控任务失败", e);
            throw new RuntimeException("查询所有任务失败：" + e.getMessage());
        }
    }
}
    